/*
1.需要添加的组件
my_project
    build
    main
        CMakeLists.txt
        idf_component.yml   <--
        main.c
    CMakeLists.txt

idf_component.yml里面的内容如下
dependencies:
  idf: ">=5.1"
  lvgl/lvgl: ">=8.*"
  esp_lvgl_port: "^1"
  atanisoft/esp_lcd_touch_xpt2046: "^1.0.1"

*/

#include <stdio.h>

#include "driver/spi_master.h" // 驱动spi的头文件
#include "esp_lvgl_port.h" // esp lvgl port组件
#include "esp_lcd_touch_xpt2046.h" // xpt2046头文件

#define LCD_SPI_PORT SPI3_HOST // 使用的spi总线

#define TOUCH_CLK 5  // 触摸的scl引脚
#define TOUCH_MOSI 3 // 触摸的mosi引脚,din
#define TOUCH_MISO 2 // 触摸的miso引脚,dout
#define TOUCH_CS 4   // 触摸的cs引脚

#define TOUCH_RST -1 // 触摸的rst引脚，触摸芯片复位
#define TOUCH_INT -1 // 触摸的int引脚，触摸芯片中断

#define LCD_H_RES 240                       // 触摸屏幕的宽
#define LCD_V_RES 340                       // 触摸屏幕的高
#define LCD_DRAW_BUF_HEIGHT (LCD_V_RES / 2) // 刷的buf设置为屏幕高的一半

#define TOUCH_SWAP_XY false
#define TOUCH_MIRROR_X false
#define TOUCH_MIRROR_Y true

void xpt2046_init(void)
{
    // 创建触摸的句柄和总线的句柄
    esp_lcd_touch_handle_t tp = NULL;
    esp_lcd_panel_io_handle_t tp_io_handle = NULL;

    // 初始化一组spi
    const spi_bus_config_t spi_bus_config = {
        .sclk_io_num = TOUCH_CLK,
        .mosi_io_num = TOUCH_MOSI,
        .miso_io_num = TOUCH_MISO,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
        .max_transfer_sz = (LCD_H_RES * LCD_DRAW_BUF_HEIGHT) * sizeof(uint16_t),
    };
    spi_bus_initialize(LCD_SPI_PORT, &spi_bus_config, SPI_DMA_CH_AUTO);

    // 初始化触摸的io面板
    esp_lcd_panel_io_spi_config_t tp_io_config = ESP_LCD_TOUCH_IO_SPI_XPT2046_CONFIG(TOUCH_CS);
    esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)LCD_SPI_PORT, &tp_io_config, &tp_io_handle);

    // 初始化xpt2046
    const esp_lcd_touch_config_t tp_cfg = {
        .x_max = LCD_H_RES,
        .y_max = LCD_V_RES,
        .levels = {
            .reset = TOUCH_RST,
            .interrupt = TOUCH_INT,
        },
        .flags = {
            .swap_xy = TOUCH_SWAP_XY,
            .mirror_x = TOUCH_MIRROR_X,
            .mirror_y = TOUCH_MIRROR_Y,
        },
    };
    esp_lcd_touch_new_spi_xpt2046(tp_io_handle, &tp_cfg, &tp);

    // 将触摸注册到lvgl
    lv_disp_t *disp = lv_disp_get_default();
    lvgl_port_touch_cfg_t touch_cfg = {
        .disp = disp,
        .handle = tp,
    };
    lvgl_port_add_touch(&touch_cfg);
}